﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Grain.Crm.DataMigrator.CrmServices;

namespace Grain.Crm.DataMigrator.Imports
{
    public class CvImport : ImportBase
    {
        public CvImport(CrmService service, WhoAmIResponse whoAmIresponse, ImportPayload importPayload)
            : base(service, whoAmIresponse, importPayload)
        {
        }

        protected override void Preprocess(out bool entityExists)
        {

            var query = new QueryByAttribute();
            query.EntityName = ThisEntityName;

            var langKeyId = ImportsHelper.GetEntityId(_service, EntityName.new_language.ToString(), new string[] { "new_name" }, new string[] { FileContent.GetByHeading(HeaderRow, "Language") });
            //var contactKeyId = ImportsHelper.GetEntityId(_service, EntityName.contact.ToString(), new string[] { "fullname" }, new string[] { FileContent.GetByHeading(HeaderRow, "Contact") });
            var cvKeyId = ImportsHelper.GetEntityId(_service, EntityName.new_curriculumvitae.ToString(), new string[] { "new_contactid", "new_languageid" },
                new string[] { ImportsGlobal.ContactId, langKeyId.ToString() });

            if(langKeyId == null)
                throw new InvalidOperationException("Could not find language in Crm:" + FileContent.GetByHeading(HeaderRow, "Language"));


            //ImportsGlobal.ContactId = contactKeyId.GetValueOrDefault().ToString();
            ImportsGlobal.LanguageId = langKeyId.GetValueOrDefault().ToString();
            
            HeaderRow += ",Contact";
            FileContent += "," + ImportsGlobal.ContactId;

            if (cvKeyId != null)
            {
                entityExists = true;

                ImportsHelper.AddKeyValueToContent(cvKeyId.GetValueOrDefault(), ThisEntityName, ref HeaderRow, ref FileContent);
            }
            else entityExists = false;


        }

        protected override void Postprocess()
        {
            var langKeyId = ImportsGlobal.LanguageId;
            var contactKeyId = ImportsGlobal.ContactId;

            //get the CV ID:
            var cv = (new_curriculumvitae) ImportsHelper.GetEntityData(_service, EntityName.new_curriculumvitae.ToString(), new string[] { "new_contactid", "new_languageid" },
                new string[] { contactKeyId.ToString(), langKeyId.ToString() }, new string[] { "new_name", "new_curriculumvitaeid" });
            
            //store it:
            ImportsGlobal.CV = cv.new_name;
            ImportsGlobal.CVId = cv.new_curriculumvitaeid.Value.ToString();
        }
    }
}
